<template>
  <!-- 科目管理 -->
  <!-- 杨友朋 -->
  <div>
    <el-card>
      <el-breadcrumb separator="/">
        <el-breadcrumb-item><i class="el-icon-s-home" style="font-weight:bold"></i>  后台管理</el-breadcrumb-item>
        <el-breadcrumb-item><b>视频管理</b></el-breadcrumb-item>
        <el-breadcrumb-item></el-breadcrumb-item>
      </el-breadcrumb>
    </el-card>
    <el-card style="margin-top:20px">
    <div style="float:left;width:200px;margin-bottom:20px">
      <div>
      <el-upload
        class="upload-demo"
        action="https://jsonplaceholder.typicode.com/posts/"
        :on-change="handleChange"
        :http-request="putinMirror"
        :file-list="fileList"
      >
        <el-button size="small" type="primary">点击上传</el-button>
        <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
      </el-upload>
    </div>
      </div>
        
        <div style="background-color: white; margin-top: 10px">
          <!-- 全查 -->
          <el-table :data="videoData" style="width: 100%; margin-top: 10px; margin-left: 15px">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column prop="filename" label="视频名称" align="center">
            </el-table-column>
            <el-table-column prop="filePath" label="视频路径" align="center">
            </el-table-column>
            <el-table-column prop="totalSize" label="视频大小" align="center">
            </el-table-column>
            <el-table-column prop="fileType" label="视频类型" align="center">
            </el-table-column>
            <el-table-column prop="createTime" label="上传时间" align="center">
            </el-table-column>
            <el-table-column prop="updateTime" label="修改时间" align="center">
            </el-table-column>
            <el-table-column fixed="right" label="操作" align="center">
              <template slot-scope="scope" >
                <!-- <el-button type="primary" @click="openUpVideo(scope.row)" v-if="scope.row.jointTitle!=null" size="small">更换课程</el-button>
                <el-button type="primary" @click="openUpVideo(scope.row)" v-if="scope.row.jointTitle==null" size="small">选择课程</el-button> -->
                <el-popconfirm confirm-button-text="确定" cancel-button-text="我再想想" icon="el-icon-info" icon-color="red" title="您确定删除吗？" @confirm="del(scope.row.id)">
                  <el-button type="primary" slot="reference" style="margin-left: 5px" size="small">删除</el-button>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页 -->
          <el-pagination
            :page-sizes="[5, 10, 15, 20]"
            :page-size="pages.pageSize"
            background
            layout="total, sizes, prev, pager, next, jumper"
            :total="pages.total"
            :current-page.sync="pages.pageNum"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          ></el-pagination>
        </div>
        
        <!-- <el-dialog :visible.sync="upHandle" width="20%">
          <el-form stripe style="width: 100%" :model="form">
            <el-form-item>
              <el-input v-model="subjectId" placeholder="请选择科目类型" ></el-input>
            </el-form-item>
            <el-form-item>
              <el-input v-model="courseId" placeholder="请选择课程" ></el-input>
            </el-form-item>
            <el-form-item>
              <el-input v-model="unitId" placeholder="请选择章节" ></el-input>
            </el-form-item>
            <el-form-item>
              <el-input v-model="form.jointId" placeholder="请选择详细课程" ></el-input>
            </el-form-item>
          </el-form>
          <el-button style=" background-color: rgb(234, 244, 255); color: rgb(96, 169, 255);" @click="addRole()" >确 定</el-button>
          <el-button @click="addHandle = false" style=" background-color: rgb(234, 244, 255); color: rgb(96, 169, 255); " >取 消</el-button >
        </el-dialog> -->
    </el-card>
  </div>
</template>

<script>
import SparkMD5 from 'spark-md5';
export default {
  data() {
    return {
      //视频文件数组
      fileList: [],
      upHandle:false,
      //条数
      total: 0,
      //视频数组
      videoData: [],
      //科目数组
      videoData: [],
      //课程数组
      videoData: [],
      //章节数组
      videoData: [],
      //课时数组
      videoData: [],
      //父级科目id
      subjectId: 0,
      courseId:0,
      unitId:0,
      jointId:0,
      //添加父级科目按钮开关
      addHandle: false,
      //添加父级科目按钮开关
      addHandleClass:false,
      //添加父级科目按钮开关
      directoryHandle: false,
      //添加父级科目按钮开关
      upClassHandleClass:false,
      //父级科目
      subjectArr:[],
      ///id数组
      ids: [],
      //添加父级科目表单
      form: {},
      pages: {
        //当前页
        pageNum: 1,
        //每页几条数据 
        pageSize: 5, 
      },
    };
  },
  created() {
    //自启动
    this.selectVideo();
  },
  methods: {
    openUpVideo(){
        this.upHandle=true
    },
    //全查视频信息
    selectVideo() {
      this.$axios
        .get("/video/selectVideo", {
          params: {
            pageNum: this.pages.pageNum,
            pageSize: this.pages.pageSize,
          },
        })
        .then((res) => {
          if ((res.code = 200)) {
            this.videoData = res.data.data.content;
            this.pages.total = res.data.data.totalSize;
          }
        })
        .catch((err) => {});
    },
    //分页
    handleSizeChange(val) {
      this.pages.pageSize = val;
      this.selectVideo();
    },
    handleCurrentChange(val) {
      this.pages.pageNum = val;
      this.selectVideo();
    },
    handleOpen(key, keyPath) {
      console.log(key, keyPath);
    },
    handleClose(key, keyPath) {
      console.log(key, keyPath);
    },
    openadd() {
      this.updateadd = true;
    },
    handleChange(file, fileList) {
        console.log('文件上传change事件:', file, fileList)
      },
      async putinMirror(file) {
        const sliceSize = 5 * 1024 * 1024; // 每个文件切片大小定为5MB
        const maxFileSize = 1 * 1024 * 1024 * 1024; // 文件大小限制为最大1个G
  
        const blob = file.file;
        const fileSize = blob.size; // 文件大小
        const fileName = blob.name; // 文件名
        const totalSlices = Math.ceil(fileSize / sliceSize); // 计算文件切片总数
        //MD5加密计算
        const reader = new FileReader();
        const identifierPrefix = await new Promise((resolve, reject) => {
        reader.onload = () => {
          const spark = new SparkMD5.ArrayBuffer();
          spark.append(reader.result);
          const hash = spark.end();
          resolve(hash); // 使用MD5计算结果作为identifier前缀
        };
        reader.onerror = () => {
          reject(new Error('文件读取错误'));
        };
        reader.readAsArrayBuffer(blob);
      });

        if (fileSize <= maxFileSize) {
            debugger
          // 循环上传分片
          for (let i = 0; i < totalSlices; i++) {
            const start = i * sliceSize;
            const chunk = blob.slice(start, Math.min(fileSize, start + sliceSize));
            const formData = new FormData();
            const fileType = file.type;
            const identifier = identifierPrefix + '-' + (i + 1); // 生成唯一标识符 // 使用原始文件名作为唯一标识符
            formData.append("identifier", identifier);
            formData.append("file", chunk);
            formData.append("chunkNumber", i + 1);
            formData.append("filename", fileName);
            formData.append("totalSize", fileSize);
            formData.append("chunkSize", totalSlices);
            formData.append("totalChunks", i + 1);
            formData.append("fileType", fileType);
            const res = await this.uploadExcleAndZip(formData); // 上传分片
            console.log(res);
                if (res.errCode === 0) {
                    setTimeout(() => {
                        if (i + 1 === totalSlices) {
                             // 上传成功后执行合并操作
                        const mergeFormData = new FormData();
                        mergeFormData.append("identifier", identifier);
                        mergeFormData.append("filename", fileName);
                        mergeFormData.append("totalChunks", totalSlices);
                        mergeFormData.append("fileType", fileType);
                        this.uploadExcleAndZip1(mergeFormData);
                        this.$message({
                            message: '上传成功',
                            type: 'success'
                        });
                        }
                    }, 1000);
                    }
                }
                } else { // 文件大小超出最大限制
                this.$message({
                    message: '文件大小超出1G',
                    type: 'error'
                });
                }
        },

       
      uploadExcleAndZip(formData) {
        // 上传分片
        return this.$axios.post('/voide/chunk', formData)
          .then(res => {
            console.log('上传成功:', formData);
            return {
              errCode: 0
            };
          });
      },
      uploadExcleAndZip1(mergeFormData) {
        debugger
        // 合并分片
        return this.$axios.post('/voide/merge', mergeFormData)
          .then(res => {
            console.log('合并成功:', mergeFormData);
          })
          .catch(error => {
            console.log('合并失败:', mergeFormData);
          });
      }
  },
};
</script>

<style>
</style>